package me.sealer.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.RoleConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import me.sealer.ssm.controller.dto.QueryRolesResponse;
import me.sealer.ssm.controller.dto.UserRolesModifyRequest;
import me.sealer.ssm.model.Role;
import me.sealer.ssm.service.RoleService;
import me.sealer.ssm.service.UserRoleService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sealer
 * @date 2016/09/27
 */
@Slf4j
@RestController
@Api(tags = "用户角色管理相关api")
@RequestMapping("/userRoleMgmt")
@RequiresRoles(value = {RoleConstant.ROLE_ADMIN})
public class UserRoleMgmtController {
    private final RoleService roleService;
    private final UserRoleService userRoleService;

    public UserRoleMgmtController(RoleService roleService, UserRoleService userRoleService) {
        this.roleService = roleService;
        this.userRoleService = userRoleService;
    }

    @ApiOperation(value = "获取用户的角色列表")
    @GetMapping(value = "/role/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse<QueryRolesResponse> queryUserRoles(
            @PathVariable(value = Dict.USERNAME) @ApiParam(value = "用户名", required = true) String username) {

        List<Role> havingRoles = userRoleService.getRolesByUsername(username);
        List<Integer> havingRolesIds = havingRoles.stream().map(Role::getId).collect(Collectors.toList());

        List<Role> allRoles = roleService.queryAllRoles();

        return new CommonResponse<>(QueryRolesResponse.builder()
                .allRoles(allRoles)
                .havingRolesIds(havingRolesIds)
                .build());
    }

    @ApiOperation(value = "修改用户角色")
    @PostMapping(value = "/modify", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse modify(
            @RequestBody UserRolesModifyRequest userRolesModifyRequest) {
        String username = userRolesModifyRequest.getUsername();
        List<Integer> rolesIds = userRolesModifyRequest.getRoles();

        userRoleService.modifyUserRoles(username, rolesIds);

        return new CommonResponse();
    }
}
